package samsung.sds.system.intercepter;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;

import samsung.sds.systemParamManagement.model.SystemParamEntity;
import samsung.sds.systemParamManagement.service.SystemParamManagementService;

public class UserOperationIPIntercepter extends BaseIntercepter {

	@Autowired
	private SystemParamManagementService systemParamManagementServiceImpl;
	
	/**
	 * 排除在外的URL地址（不进行拦截的）
	 */
	private String excludeUrls;

	/**
	 * 跳转的URL
	 */
	private String redirectUrl;

	public void setRedirectUrl(String redirectUrl) {
		this.redirectUrl = redirectUrl;
	}
	
	public void setExcludeUrls(String excludeUrls) {
		this.excludeUrls = excludeUrls;
	}
	
	public String getRedirectUrl() {
		return redirectUrl;
	}

	public String getExcludeUrls() {
		return excludeUrls;
	}

	@Override
	public boolean checkLogic(HttpServletRequest request, HttpServletResponse response, Object object)
			throws Exception {
		String ip = request.getRemoteAddr();
		Collection<SystemParamEntity> blackUserList = new ArrayList<SystemParamEntity>();

		getBlackUsers(blackUserList);
		
		for (SystemParamEntity blackUser : blackUserList) {
			// 如果用户的IP在BLACKLISTUSERS里,则跳转到没有权限页面
			if (ip.matches(blackUser.getParamVal())) {
				// 绑定黑名单用户的详细描述
				ServletContext servletContext = request.getSession()
						.getServletContext();
				servletContext.setAttribute("system_ip_blackUser_desc",
						blackUser.getParamDesc());
				return true;
			}
		}
		return false;
	}

	@Override
	public boolean isHavePassport(HttpServletRequest request, HttpServletResponse response, Object object) {
		return false;
	}
	
	/**
	 * 获得黑名单用户的列表
	 * 
	 * @param blackUserList
	 */
	private void getBlackUsers(
			Collection<SystemParamEntity> blackUserList) {
		Map<String, SystemParamEntity> systemParam = systemParamManagementServiceImpl.getSystemParamCache();
		for (String key:systemParam.keySet()) {
			
			if (key.indexOf("system_ip_blackUser") >= 0) {
				blackUserList.add(systemParam.get(key));
			}
		}
	}
	
	@Override
	public Map<String, Object> getParam() {
		Map<String , Object> map = new HashMap<String, Object>();
		map.put("excludeUrls", excludeUrls);
		map.put("redirectUrl", redirectUrl);
		return map;
	}
}
